package gui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;

import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import parts.APart;
import parts.CompositePart;
import controllers.PartManagementController;

public class PartsTree extends JTree {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private PartsTreePopupMenu popup;
	private JTextField partNameField;
	private JTextField partValueField;
	
	public PartsTree(JTextField partName, JTextField partValue) {
		partNameField = partName;
		partValueField = partValue;
		init();
	}
	
	private void nodeSelected(TreeSelectionEvent e) {
		TreePath path = e.getPath();
		APart part = (APart) ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject();
		partNameField.setText(part.getName());
		partValueField.setText(Double.toString(part.getValue()));
	}
	
	private void init() {
		CompositePart part = PartManagementController.getInstance().getPart();
		DefaultTreeModel model = (DefaultTreeModel) getDefaultTreeModel();
		this.setModel(model);
		
		popup = new PartsTreePopupMenu(this);
		this.setComponentPopupMenu(popup);
		
		if (part == null) {
			DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new CompositePart("Part", 0.0));
			model.setRoot(rootNode);
		} 
		else if (part.isComposite()) {
			DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(part);
			model.setRoot(rootNode);
		}
		
		this.addTreeSelectionListener(new TreeSelectionListener() {

			@Override
			public void valueChanged(TreeSelectionEvent e) {
				nodeSelected(e);
			}
			
		});
	}
}
